﻿using System;
using System.Data;
using System.IO;
using System.Text;
using System.Xml;

namespace ZYCommon
{
    

    public class XMLHttpServer
    {
        private const string c_NullFlag = "[NULL]";
        private IDbConnection myConnection;
        public static string SessionID;

        public static int AppendXMLContent(StringBuilder myStr, string strText)
        {
            if (strText != null)
            {
                int length = strText.Length;
                for (int i = 0; i < length; i++)
                {
                    char ch = strText[i];
                    switch (ch)
                    {
                        case '<':
                            myStr.Append("&lt;");
                            break;

                        case '>':
                            myStr.Append("&gt;");
                            break;

                        case '&':
                            myStr.Append("&amp;");
                            break;

                        default:
                            myStr.Append(ch);
                            break;
                    }
                }
                return length;
            }
            myStr.Append("[NULL]");
            return 0;
        }

        public virtual bool Authorize(string vUserName, string vPassword, string vType)
        {
            return true;
        }

        public static string CreateErrorMessage(string strError)
        {
            StringBuilder myStr = new StringBuilder();
            myStr.Append("<?xml version='1.0' encoding='GB2312'?><xmlhttpconnection error='1' version='1.0' >");
            AppendXMLContent(myStr, strError);
            myStr.Append("</xmlhttpconnection>");
            return myStr.ToString();
        }

        public static string CreateTestCommand()
        {
            return "<xmlhttpconnection text=\"[testconnection]\" data=\"test_ok_中文测试\" />";
        }

        public string Execute(Stream InputStream)
        {
            XmlDocument inputXMLDoc = new XmlDocument();
            try
            {
                inputXMLDoc.Load(InputStream);
                return this.Execute(inputXMLDoc);
            }
            catch (Exception exception)
            {
                return CreateErrorMessage(exception.ToString());
            }
        }

        public string Execute(XmlDocument InputXMLDoc)
        {
            int num = 0;
            StringWriter w = null;
            XmlTextWriter writer2 = null;
            try
            {
                string attribute = InputXMLDoc.DocumentElement.GetAttribute("text");
                string vType = InputXMLDoc.DocumentElement.GetAttribute("type");
                string vUserName = InputXMLDoc.DocumentElement.GetAttribute("user");
                string vPassword = InputXMLDoc.DocumentElement.GetAttribute("pwd");
                string str5 = ExecuteTestCommand(InputXMLDoc);
                if (str5 != null)
                {
                    return str5;
                }
                if (!this.Authorize(vUserName, vPassword, vType))
                {
                    return CreateErrorMessage("用户" + vUserName + "的操作请求被拒绝");
                }
                w = new StringWriter();
                writer2 = new XmlTextWriter(w);
                if (InputXMLDoc.DocumentElement.GetAttribute("indent") == "1")
                {
                    writer2.Indentation = 4;
                    writer2.IndentChar = ' ';
                    writer2.Formatting = Formatting.Indented;
                }
                writer2.WriteStartDocument();
                writer2.WriteStartElement("xmlhttpconnection");
                writer2.WriteAttributeString("version", "1.0");
                writer2.WriteAttributeString("session", SessionID);
                if ((this.myConnection != null) && (this.myConnection.State == ConnectionState.Open))
                {
                    using (IDbCommand command = this.myConnection.CreateCommand())
                    {
                        command.CommandText = attribute;
                        foreach (XmlNode node in InputXMLDoc.DocumentElement.ChildNodes)
                        {
                            if (!(node.Name == "param") || !(node is XmlElement))
                            {
                                continue;
                            }
                            IDbDataParameter parameter = command.CreateParameter();
                            string innerText = node.InnerText;
                            if (innerText == "[NULL]")
                            {
                                parameter.Value = "";
                            }
                            else
                            {
                                parameter.Value = innerText;
                            }
                            command.Parameters.Add(parameter);
                        }
                        switch (vType)
                        {
                            case "0":
                            {
                                IDataReader reader = command.ExecuteReader();
                                int fieldCount = reader.FieldCount;
                                for (int i = 0; i < fieldCount; i++)
                                {
                                    writer2.WriteAttributeString("f" + i.ToString(), reader.GetName(i).ToLower());
                                }
                                while (reader.Read())
                                {
                                    num++;
                                    writer2.WriteStartElement("r");
                                    for (int j = 0; j < fieldCount; j++)
                                    {
                                        writer2.WriteElementString("f" + j.ToString(), reader.IsDBNull(j) ? "[NULL]" : reader[j].ToString());
                                    }
                                    writer2.WriteEndElement();
                                }
                                reader.Close();
                                break;
                            }
                            case "1":
                                writer2.WriteString(command.ExecuteNonQuery().ToString());
                                break;
                        }
                    }
                }
                else
                {
                    writer2.WriteAttributeString("error", "1");
                    writer2.WriteString("数据库未打开");
                }
                writer2.WriteEndElement();
                writer2.WriteEndDocument();
                writer2.Flush();
                string str7 = w.ToString();
                writer2.Close();
                writer2 = null;
                int index = str7.IndexOf("?>");
                if (index > 0)
                {
                    str7 = str7.Substring(index + 2);
                }
                return str7;
            }
            catch (Exception exception)
            {
                if (writer2 != null)
                {
                    writer2.Close();
                }
                return CreateErrorMessage(exception.ToString());
            }
        }

        public static string ExecuteTestCommand(XmlDocument InputXMLDoc)
        {
            if (InputXMLDoc.DocumentElement.GetAttribute("text") == "[testconnection]")
            {
                if (InputXMLDoc.DocumentElement.GetAttribute("data") == "test_ok_中文测试")
                {
                    return "test_ok_中文测试";
                }
                return "错误的输入编码";
            }
            return null;
        }

        public IDbConnection Connection
        {
            get
            {
                return this.myConnection;
            }
            set
            {
                this.myConnection = value;
            }
        }
    }
}

